package com.szp.lagou.mq.rocketmq.controller;

import com.szp.lagou.mq.rocketmq.constant.Constants;
import com.szp.lagou.mq.rocketmq.pojo.Order;
import com.szp.lagou.mq.rocketmq.properties.SecKillTimeProperties;
import com.szp.lagou.mq.rocketmq.service.OrderService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;

@Controller
public class KillController {
    @Autowired
    SecKillTimeProperties secKillTimeProperties;
    @Autowired
    OrderService orderService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @RequestMapping("/setStock")
    @ResponseBody
    public String openbuy(String count) {
        redisTemplate.opsForValue().set(Constants.KILL_REDIS_KEY, count);
        return "ok";
    }

    @RequestMapping("/")
    public String index(Model model){
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime ldt = LocalDateTime.parse(secKillTimeProperties.getStartTime(), dtf);
        System.out.println(ldt);
        LocalDateTime expireTime = ldt.plusSeconds(secKillTimeProperties.getDuration());
        System.out.println(expireTime);
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        if(now.isAfter(expireTime)){// 抢购已结束
            System.out.println("抢购已结束");
            model.addAttribute("status", "0");
            model.addAttribute("leftTime", 0);
            return "index";
        }else if(now.isBefore(ldt)){//未开始
            System.out.println("抢购未开始");
            model.addAttribute("status", "2");
            model.addAttribute("leftTime", 0);
            return "index";
        }

        long leftTime = expireTime.toEpochSecond(ZoneOffset.of("+8")) -now.toEpochSecond(ZoneOffset.of("+8"));
        System.out.println(expireTime.getSecond());
        System.out.println(now.getSecond());
        System.out.println(leftTime);
        String availableQuantity = (String)redisTemplate.opsForValue().get(Constants.KILL_REDIS_KEY);
        String stock;
//        if(null == availableQuantity) {
//            availableQuantity = String.valueOf(100);
//            redisTemplate.opsForValue().set(Constants.KILL_REDIS_KEY, "100");
//        }
        stock = String.valueOf(availableQuantity);
        if(Integer.parseInt(stock) > 0){
            model.addAttribute("stock", stock);
            model.addAttribute("status", "1");
            model.addAttribute("leftTime", leftTime);
        }else {
            model.addAttribute("stock", "0");
            model.addAttribute("leftTime", 0);
            model.addAttribute("status", "0");

        }
        model.addAttribute("startTime", secKillTimeProperties.getStartTime());
        model.addAttribute("duration", secKillTimeProperties.getDuration());

        return "index";
    }

    @RequestMapping("/kill")
    public String kill(Model model){
        //redis stock -1
        String availableQuantity = (String)redisTemplate.opsForValue().get(Constants.KILL_REDIS_KEY);
        if (Integer.parseInt(availableQuantity) < 1) {
            return "failure";
        }
        // send message to MQ
        Order order = new Order();
        order.setId(UUID.randomUUID().toString());
        order.setProductId(Constants.PRODUCT_ID);
        order.setPrice(Constants.PRODUCT_PRICE);
        order.setStatus(Constants.ORDER_STATUS_CREATED);
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpleDateFormat.format(date);
        order.setCreateTime(date);
        order.setUpdateTime(date);

        model.addAttribute("orderId", order.getId());
        rocketMQTemplate.convertAndSend(Constants.KILL_ORDER_TOPIC, order);
        System.out.println(order);
        System.out.println("rocketmq发送成功");
        redisTemplate.opsForValue().decrement(Constants.KILL_REDIS_KEY, 1);
        System.out.println("redis数据扣除成功");

        return "order";
    }

    @RequestMapping("/pay")
    public String payOrder(@RequestParam("orderId") String id, Model model) {
        orderService.payOrder(id);
        model.addAttribute("orderId", id);
        return "success";
    }
}
